package com.feng.code.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.feng.code.annotation.AuthCheck;
import com.feng.code.common.BaseResponse;
import com.feng.code.common.DeleteRequest;
import com.feng.code.common.ResultUtils;
import com.feng.code.constant.UserConstant;
import com.feng.code.exception.BusinessException;
import com.feng.code.exception.ErrorCode;
import com.feng.code.exception.ThrowUtils;
import com.feng.code.pojo.dto.admin.UserAddRequest;
import com.feng.code.pojo.dto.admin.UserQueryRequest;
import com.feng.code.pojo.dto.admin.UserUpdateRequest;
import com.feng.code.pojo.dto.user.UserInfoUpdateRequest;
import com.feng.code.pojo.dto.user.UserLoginRequest;
import com.feng.code.pojo.dto.user.UserPwdUpdateRequest;
import com.feng.code.pojo.dto.user.UserRegisterRequest;
import com.feng.code.pojo.entity.User;
import com.feng.code.pojo.vo.UserVO;
import com.feng.code.sevice.UserService;
import com.feng.code.utils.UserUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Resource
    private UserService userService;

    /**
     * 注册账号
     * @param userRegisterRequest 注册账号请求体
     * @return 账号id
     */
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        ThrowUtils.throwIf(userRegisterRequest == null, ErrorCode.PARAMS_ERROR);
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        long userId = userService.userRegister(userAccount, userPassword, checkPassword);
        return ResultUtils.success(userId);
    }

    /**
     * 用户登录
     * @param userLoginRequest 用户登录请求体
     * @param request 请求
     * @return 脱敏后的用户信息
     */
    @PostMapping("/login")
    public BaseResponse<UserVO> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(userLoginRequest == null, ErrorCode.PARAMS_ERROR);
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        UserVO userVO = userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(userVO);
    }

    /**
     * 获取当前登录用户
     * @param request 请求
     * @return 脱敏后的当前用户信息
     */
    @PostMapping("/get/login")
    public BaseResponse<UserVO> getLoginUser(HttpServletRequest request) {
        User user = userService.getLoginUser(request);
        return ResultUtils.success(UserUtils.objToVo(user));
    }

    /**
     * 更新个人信息
     * @param userInfoUpdateRequest 信息更新请求体
     * @return true
     */
    @PostMapping("/info/update")
    public BaseResponse<Boolean> userInfoUpdate(@RequestBody UserInfoUpdateRequest userInfoUpdateRequest) {
        ThrowUtils.throwIf(userInfoUpdateRequest == null, ErrorCode.PARAMS_ERROR);
        Long id = userInfoUpdateRequest.getId();
        if (id == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = new User();
        BeanUtils.copyProperties(userInfoUpdateRequest, user);
        boolean flag = userService.updateById(user);
        if (!flag) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "更新失败");
        }
        return ResultUtils.success(true);
    }

    /**
     * 更新密码
     * @param userPwdUpdateRequest 密码更新请求体
     * @param request 请求
     * @return true
     */
    @PostMapping("/pwd/update")
    public BaseResponse<Boolean> userPwdUpdate(@RequestBody UserPwdUpdateRequest userPwdUpdateRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(userPwdUpdateRequest == null, ErrorCode.PARAMS_ERROR);
        String oldPwd = userPwdUpdateRequest.getOldPassword();
        String newPwd = userPwdUpdateRequest.getNewPassword();
        String checkPwd = userPwdUpdateRequest.getCheckPassword();
        boolean flag = userService.userPwdUpdate(oldPwd, newPwd, checkPwd, request);
        if (!flag) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "更新失败");
        }
        return ResultUtils.success(true);
    }

    /**
     * 退出登录
     * @param request 请求
     * @return 是否退出成功
     */
    @PostMapping("/logout")
    public BaseResponse<Boolean> userLogout(HttpServletRequest request) {
        ThrowUtils.throwIf(request == null, ErrorCode.PARAMS_ERROR);
        boolean flag = userService.logout(request);
        return ResultUtils.success(flag);
    }

    /**
     * 创建用户（仅管理员）
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.SUPER_ROLE)
    public BaseResponse<Long> addUser(@RequestBody UserAddRequest userAddRequest) {
        ThrowUtils.throwIf(userAddRequest == null, ErrorCode.PARAMS_ERROR);
        User user = new User();
        BeanUtil.copyProperties(userAddRequest, user);
        // 默认密码 12345678
        final String DEFAULT_PASSWORD = "12345678";
        String encryptPassword = UserUtils.getEncryptPassword(DEFAULT_PASSWORD);
        user.setUserPassword(encryptPassword);
        boolean result = userService.save(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(user.getId());
    }

    /**
     * 根据 id 获取用户（仅管理员）
     */
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.SUPER_ROLE)
    public BaseResponse<User> getUserById(long id) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        User user = userService.getById(id);
        ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(user);
    }

    /**
     * 根据 id 获取包装类
     */
    @GetMapping("/get/vo")
    public BaseResponse<UserVO> getUserVOById(long id) {
        BaseResponse<User> response = getUserById(id);
        User user = response.getData();
        return ResultUtils.success(UserUtils.objToVo(user));
    }

    /**
     * 删除用户（仅管理员）
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.SUPER_ROLE)
    public BaseResponse<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = userService.removeById(deleteRequest.getId());
        return ResultUtils.success(b);
    }

    /**
     * 更新用户（仅管理员）
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.SUPER_ROLE)
    public BaseResponse<Boolean> updateUser(@RequestBody UserUpdateRequest userUpdateRequest) {
        if (userUpdateRequest == null || userUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = new User();
        BeanUtil.copyProperties(userUpdateRequest, user);
        boolean result = userService.updateById(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 分页获取用户封装列表（仅管理员）
     *
     * @param userQueryRequest 查询请求参数
     */
    @PostMapping("/list/page/vo")
    @AuthCheck(mustRole = UserConstant.SUPER_ROLE)
    public BaseResponse<Page<UserVO>> listUserVOByPage(@RequestBody UserQueryRequest userQueryRequest) {
        ThrowUtils.throwIf(userQueryRequest == null, ErrorCode.PARAMS_ERROR);
        long pageNum = userQueryRequest.getPageNum();
        long pageSize = userQueryRequest.getPageSize();
        Page<User> userPage = userService.page(new Page<>(pageNum, pageSize),
                UserUtils.getQueryWrapper(userQueryRequest));
        // 数据脱敏
        Page<UserVO> userVOPage = new Page<>(pageNum, pageSize, userPage.getTotal());
        List<UserVO> userVOList = UserUtils.getUserVoList(userPage.getRecords());
        userVOPage.setRecords(userVOList);
        return ResultUtils.success(userVOPage);
    }

}
